<script>
import L from 'leaflet';
import { WGS84ToGCJ02 } from 'istrong-map-coordinate-transformation';
import cloneDeep from 'lodash/cloneDeep';
import orderBy from 'lodash/orderBy';
import isEmpty from 'lodash/isEmpty';
import vgMap from '../../components/Map.vue';
import Position from '../../libs/leaflet-positionmarker';

let sortByField = (data) => {
  let ls = orderBy(data, [function (o, a) {
    return o.options.feature.level_index;
  }, function (o, a) {
    return o.options.feature.val || -1;
  }], ['desc', 'desc']);
  return ls;
}

let legend = {
  'level--1': {
    color: '#ffffff',
    level: '0',
    level_index: '-1',
    level_name: '无积水'
  },
  'level-1': {
    color: '#0000FE',
    level: '0.01-0.05',
    level_index: '1',
    level_name: '轻微积水'
  },
  'level-2': {
    color: '#FFFF00',
    level: '0.05-0.25',
    level_index: '2',
    level_name: '一般积水'
  },
  'level-3': {
    color: '#FA800A',
    level: '0.25-0.5',
    level_index: '3',
    level_name: '较大积水'
  },
  'level-4': {
    color: '#FE0000',
    level: '0.5以上',
    level_index: '4',
    level_name: '严重积水'
  }
}
export default {
  name: 'waterloggingMap',
  components: {
    'vg-map': vgMap
  },
  props: {
    beginTime: {
      type: String,
      required: true
    },
    endTime: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      default: []
    },
    positionMarker: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      crs: 'EPSG3857',
      zoom: 8,
      center: [26, 119],
      baseLayers: [],
      thematicLayers: [],
      zoomControl: {},
      layersControl: {},
      vStationLayerName: 'vWaterLoggingStation',//矢量站点名称
      vStationMarkers: {}
    }
  },
  watch: {
    data: function (val) {
      this._loadVStationsToMap();
    },
    positionMarker: function (val) {
      this._startPosition();
    }
  },
  mounted () {
    this._loadVStationsToMap();
    this._startPosition();
  },
  methods: {
    _loadVStationsToMap () {
      let vMap = this.$refs.map;
      vMap.clearLayer(this.vStationLayerName);
      if (!this.data || this.data.length === 0) {
        return;
      }
      let layerOpts = {
        latlngBounds: L.latLngBounds([-20, 60], [60, 200]),
        onlyCollisionTooltip: true,
        markerOffset: [1, 1],
        tooltipOffset: [0, 0],
        map: vMap.Map,
        sortByField: sortByField
      };
      this.vStationMarkers = {};
      vMap.addCollisionLayer(this.vStationLayerName, layerOpts, this.data, this._vStationsMarkerInit)
    },
    _vStationsMarkerInit (stationInfo, layer) {
      stationInfo.lat = stationInfo.lat || stationInfo.latitude;
      stationInfo.lng = stationInfo.lng || stationInfo.longitude;
      if (!stationInfo.lat || !stationInfo.lng) {
        return;
      }
      stationInfo.id = stationInfo.id || stationInfo._id;
      let vector = this.vStationMarkers;
      let gcj02 = WGS84ToGCJ02({ lng: stationInfo.lng, lat: stationInfo.lat });
      let latlng = L.latLng(gcj02.lat, gcj02.lng);
      if (vector[stationInfo.id]) {
        layer.removeLayer(vector[stationInfo.id]);
      }

      let fillColor = legend['level-' + stationInfo.level_index].color;

      let marker = new L.CircleMarker(latlng,
        {
          color: '#929292',
          weight: 1,
          opacity: 1,
          fill: true,
          fillColor: fillColor,
          fillOpacity: 1,

          radius: 8,
          feature: stationInfo,
          renderer: this.$refs.map.RenderCanvas
        });
      marker.on('click', this._showChartInfo, this);

      let toolTip = (new L.Tooltip({
        permanent: false,
        interactive: true,
        direction: 'right',
        offset: [6, 0],
        mapPreclickToClose: false,
        className: 'commonTooltip',
        feature: stationInfo
      }, marker)).setContent(stationInfo.name + (stationInfo.val !== undefined ? '<br/>' + stationInfo.val : ''));
      toolTip.on('click', this._showChartInfo, this);
      marker.bindTooltip(toolTip);

      vector[stationInfo.id] = marker;
      return marker;
    },
    _showChartInfo (e) {
      let feature = e.target.options.feature;
      this.$emit('showChartInfo', feature);
    },
    onChangeShowType () {
      this.$emit('changeShowType', 'list');
    },
    onOpenFilterPanel () {
      this.$emit('setFilterConditions', true);
    },
    _startPosition () {
      if (this.positionMarker === '') {
        return;
      }
      if (this.positionMarker === 'center') {
        Position.setCenterView(this.$refs.map.Map, this.$AppConfig.map.module.waterlogging.center)
        this.$emit('positionEnd');
        return;
      }
      Position.startPosition(this, this.$refs.map.Map, this.positionMarker, this.vStationMarkers, 12);
      this.$emit('positionEnd');
    }
  },
  created () {
    let mapConfig = this.$AppConfig.map;
    this.crs = mapConfig.crs;
    this.zoom = mapConfig.zoom;
    this.center = mapConfig.center;
    this.baseLayers = cloneDeep(mapConfig.baseLayers);
    this.thematicLayers = cloneDeep(mapConfig.thematicLayers);
    this.zoomControl = mapConfig.zoomControl;
    this.layersControl = mapConfig.layersControl;

    let moduleConfig = mapConfig.module ? mapConfig.module.waterlogging : null;
    if (moduleConfig) {
      let baseLayer = moduleConfig.baseLayer;
      if (baseLayer) {
        this.baseLayers.forEach(item => {
          item.checked = (item.id === baseLayer ||
            item.name === baseLayer);
        });
      }
      this.zoom = moduleConfig.zoom || this.zoom;
      this.center = moduleConfig.center || this.center;
      if (!isEmpty(moduleConfig.thematicLayers)) {
        let thematicLayers = [];
        this.thematicLayers.forEach(item => {
          if (moduleConfig.thematicLayers[item.id + '']) {
            thematicLayers.push(assign(item, moduleConfig.thematicLayers[item.id + '']));
          }
        });
        this.thematicLayers = thematicLayers;
      }
    }
  },
  beforeDestroy () {
  }
}
</script>
<template>
  <div id="mapViewer">
    <vg-map
      :crs="crs"
      :baseLayers="baseLayers"
      :thematicLayers="thematicLayers"
      :zoom="zoom"
      :center="center"
      :zoomControl="zoomControl"
      :layersControl="layersControl"
      ref="map"
    ></vg-map>
    <div class="mapViewer-TopRight-Controls">
      <div
        class="btChangeRouterList"
        @click="onChangeShowType"
      >
        <span class="ion-ios-list"></span>
      </div>
      <div
        class="mapViewer-ButtonFilter"
        @click="onOpenFilterPanel"
      >
        <img src="../../assets/filter.png" />
      </div>
    </div>
  </div>
</template>
<style>
</style>